Code
library(gapminder)
library(tidyverse)
library(plotly)Tony Duan
October 12, 2022
Rows: 1,704
Columns: 6
$ country <fct> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", …
$ continent <fct> Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, …
$ year <int> 1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, …
$ lifeExp <dbl> 28.801, 30.332, 31.997, 34.020, 36.088, 38.438, 39.854, 40.8…
$ pop <int> 8425333, 9240934, 10267083, 11537966, 13079460, 14880372, 12…
$ gdpPercap <dbl> 779.4453, 820.8530, 853.1007, 836.1971, 739.9811, 786.1134, …
准备数据
gapminder_data_cn_us_2007=gapminder_data %>% filter(country %in% c('China','United States')) %>% filter(year==year)
gapminder_data_cn_2007=gapminder_data %>% filter(country %in% c('China')) %>% filter(year==year)
gapminder_data_2007=gapminder_data %>% filter(year==2007)
glimpse(gapminder_data_cn_us_2007)Rows: 24
Columns: 6
$ country <fct> "China", "China", "China", "China", "China", "China", "China…
$ continent <fct> Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, Asia, …
$ year <int> 1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, …
$ lifeExp <dbl> 44.00000, 50.54896, 44.50136, 58.38112, 63.11888, 63.96736, …
$ pop <int> 556263527, 637408000, 665770000, 754550000, 862030000, 94345…
$ gdpPercap <dbl> 400.4486, 575.9870, 487.6740, 612.7057, 676.9001, 741.2375, …
人均寿命和人均GPD的散点图
GGplot
Plotly
人均寿命和人均GPD的散点图
GGplot

Plotly
https://datacarpentry.org/R-ecology-lesson/04-visualization-ggplot2 https://plotly.com/r/
---
title: "用ggplot和Plotly画散点图"
author: "Tony Duan"
date: "2022-10-12"
categories: [Ploting]
execute:
warning: false
error: false
format:
html:
code-fold: show
code-tools: true
---
## 1. 散点图
```{r}
library(gapminder)
library(tidyverse)
library(plotly)
```
```{r}
gapminder_data=gapminder
glimpse(gapminder_data)
```
准备数据
```{r}
gapminder_data_cn_us_2007=gapminder_data %>% filter(country %in% c('China','United States')) %>% filter(year==year)
gapminder_data_cn_2007=gapminder_data %>% filter(country %in% c('China')) %>% filter(year==year)
gapminder_data_2007=gapminder_data %>% filter(year==2007)
glimpse(gapminder_data_cn_us_2007)
```
人均寿命和人均GPD的散点图
GGplot
```{r}
ggplot(data = gapminder_data_2007 , aes(x = lifeExp, y = gdpPercap)) +
geom_point()
```
Plotly
```{r}
plot_ly(data = gapminder_data_2007, x = ~lifeExp, y = ~gdpPercap)
```
人均寿命和人均GPD的散点图
GGplot
```{r}
#| output: false
ggplot(data = gapminder_data_2007 , aes(x = lifeExp, y = gdpPercap)) +
geom_point(aes(color = continent ))
ggsave("feature.png")
```

Plotly
```{r}
plot_ly(data = gapminder_data_2007, x = ~lifeExp, y = ~gdpPercap,color = ~continent)
```
## Reference
https://datacarpentry.org/R-ecology-lesson/04-visualization-ggplot2
https://plotly.com/r/